<template>
  <div class="detail_container">
    <!-- <div class="sp" ref="sp"></div> -->
    <div class="header" ref="sp" :style="{opacity: show}">
      <div @click="tab(0)" :class="['nn_tiem', tabIndex == 0 ? 'active' : '']">
        <span>商品</span>
      </div>
      <div @click="tab(1)" :class="['nn_tiem', tabIndex == 1 ? 'active' : '']">
        <span>评价</span>
      </div>
      <div @click="tab(2)" :class="['nn_tiem', tabIndex == 2 ? 'active' : '']">
        <span>推荐</span>
      </div>
      <div @click="tab(3)" :class="['nn_tiem', tabIndex == 3 ? 'active' : '']">
        <span>详情</span>
      </div>
    </div>

    <slider-image :slider_image="slider_image"></slider-image>
    <my-message :message="message"></my-message>
    <div class="select" @click="openAttr">
      <div class="ss_lef">
        已选择:&nbsp;&nbsp;<span>{{ suk }}</span>
      </div>
      <div class="icon">
        <img src="../../assets/icon/common/right_arrow.svg" alt="" />
      </div>
    </div>

    <div class="pj" ref="pj">
      <div class="pl">用户评价(0)</div>
      <div class="pr">
        <span>0%</span>
        好评价
        <i></i>
      </div>
    </div>

    <div class="tj" ref="tj"></div>
    <recommend-product :good_list="good_list"></recommend-product>

    <div class="xq" ref="xq"></div>
    <my-introduce :description="description"></my-introduce>

    <!-- <transition name="attr">
        <my-size v-if="isShowAttr" 
        :productAttr="productAttr"
        :productValue="productValue" 
        :store_name="message.store_name"
        :images="slider_image"
        @closeAttr="closeAttr"></my-size>
    </transition> -->

    <!-- <footer class="footer">
      <div class="dj_com kefu" @click="addCart">
        <img src="../../assets/icon/detail/kefu_66.png" alt="" />
        <div>客服</div>
      </div>
      <div class="dj_com collect" @click="addCollection">
        <img
          src="../../assets/icon/detail/xin_66.png"
          alt=""
          v-if="isCollect"
        />
        <img src="../../assets/icon/detail/xin_661.png" alt="" v-else />

        <div>收藏</div>
      </div>
      <div class="dj_com cart" @click="goCart">
        <img src="../../assets/icon/detail/cart_66.png" alt="" />
        <div>购物车</div>
      </div>
      <div class="btns">
        <div class="addCart" @click="openAttr">加入购物车</div>
        <div :class="['buy', isBuy == '已售罄' ? 'bgc1' : 'bgc2']">
          {{ isBuy }}
        </div>
      </div>
    </footer> -->

    <my-footer
      :isBuy="isBuy"
      :productId="productId"
      :count="count"
      :unique="unique"
      :userCollect="userCollect"
      :isShowAttr="isShowAttr"
      @openAttr="openAttr2"
      @share-isCollect="getCollect"
    ></my-footer>

    <div class="mask" v-if="isShowAttr" @click="closeAtter"></div>

    <transition name="attr">
      <div class="MySize" v-if="isShowAttr">
        <div class="info">
          <div class="img">
            <img :src="image | changeImage(slider_image[0])" alt="" />
          </div>
          <div class="inf">
            <div class="store_name">{{ message.store_name }}</div>
            <div class="tp">
              ￥<span class="price">{{
                price | changeImage(message.price)
              }}</span>
              <span class="store"
                >库存:{{ stock | changeStock(message.stock) }}</span
              >
            </div>
          </div>
        </div>

        <div class="box" v-if="attr">
          <div class="ty_com size" v-if="sizeVissably">
            <div class="ty_td size_td">尺码</div>
            <div class="item" ref="size">
              <span
                v-for="(item, i) in sizeList"
                :key="i"
                :class="index == item.attr ? 'active' : ''"
                @click="clickSize(item.attr)"
              >
                {{ item.attr }}
              </span>
            </div>
          </div>
          <div class="ty_com color" v-if="colorVissably">
            <div class="ty_td color_td">颜色</div>
            <div class="item">
              <span
                v-for="(ele, i) in colorList"
                :key="i"
                :class="square == ele.attr ? 'active' : ''"
                @click="clickColor(ele.attr)"
              >
                {{ ele.attr }}
              </span>
            </div>
          </div>
        </div>

        <div class="ty_com count">
          <div class="ty_td count_td">数量</div>
          <div class="count_com">
            <div @click="subCount">-</div>
            <div class="num">{{ count }}</div>
            <div @click="addCount">+</div>
          </div>
        </div>

        <div class="closeBtn" @click="closeAttr">
          <img src="../../assets/icon/detail/close_8a.png" alt="" />
        </div></div
    ></transition>
  </div>
</template>


<script>
import MyMessage from "@/views/detail/Message.vue";
import SliderImage from "@/views/detail/SliderImage.vue";
import RecommendProduct from "@/views/detail/RecommendProduct.vue";
import MyIntroduce from "@/views/detail/MyIntroduce.vue";
import MyFooter from "@/views/detail/Footer.vue";
// import MySize from "@/views/detail/MySize.vue";

import { mapMutations } from "vuex";

export default {
  data() {
    return {
      productId: 0,
      // 基本信息栏
      message: {},
      // 轮播tu
      slider_image: [],
      // 精品推荐
      good_list: [],
      // 产品介绍
      description: "",
      // 属性 选择尺码
      productAttr: [],
      // 属性组合
      productValue: [],
      // 显示属性选择器
      isShowAttr: false,
      isXia: true,
      // 是否收藏
      isCollect: false,

      //
      sizelist: [],
      colorList: [],

      image: "",
      price: "",
      sales: "",
      stock: null,
      suk: "",
      unique: "",
      color: "",
      size: "",

      colorVissably: false, // 控制颜色显示
      sizeVissably: false, // 控制尺码显示

      index: 0, // 点击选择对应尺码
      square: 0, // 点击选择对应颜色
      userCollect: false, // 是否收藏
      attrObj: {},

      key: "",

      count: 1,
      tabIndex: 0,
      distance: [],
      flag: true,
      show:0,
      ds:0,
    };
  },
  computed: {
    attr() {
      if (this.productAttr.length == 0) {
        return false;
      } else {
        return true;
      }
    },

    isBuy() {
      if (this.stock == 0) {
        return "已售罄";
      } else {
        return "立即购买";
      }
    },
  },

  watch: {
    ds(val){
      if(val <= 0 ){
        this.show = 0
      }else
      if(val > 50 && val < 90){
        this.show = 0.5
      }else if(val >= 90 ){
        this.show = 1
      }
    }
  },

  filters: {
    changeImage(v1, v2) {
      return v1 == "" ? v2 : v1;
    },
    changeStock(v1, v2) {
      return v1 == null ? v2 : v1;
    },
  },

  components: {
    MyMessage,
    SliderImage,
    RecommendProduct,
    MyIntroduce,
    MyFooter,
    // MySize,
  },
 
  created() {
    this.$router.afterEach((to,from,next)=>{

      window.scrollTo(0,0)
    })
    this.productId = this.$route.params.id;

   
    
    this.initDetail();
    
  },
  methods: {
    ...mapMutations("collect", ["addCollect"]),
    ...mapMutations("collect", ["removeCollect"]),
    goCart() {
      this.$router.push("/cart");
    },
    closeAtter(){
      if(this.isShowAttr){
        this.isShowAttr = false
      }
    },
    // 添加购物车
    addCart() {
      let token = localStorage.getItem("token");
      console.log(token);
      let url = "/api/cart/add";
      let data = {
        cartNum: this.count,
        new: 0,
        productId: this.productId,
        uniqueId: this.unique,
      };
      let pro = axios({
        method: "Post",
        url: url,
        data: data,
        headers: {
          "Authori-zation": "Bearer " + token,
        },
      })
        .then((res) => {
          console.log("成功", res.data);
        })
        .catch((err) => {
          console.log("失败");
        });
    },

    initDetail() {
      let token = localStorage.getItem("token");
      let url = `/api/product/detail/${this.productId}`;
      let pro = axios({
        method: "get",
        url: url,
        headers: {
          "Authori-zation": "Bearer " + token,
        },
      })
        .then((res) => {
          console.log("商品详情获取成功", res.data);
          let { status, data } = res.data;
          let { storeInfo, good_list, productAttr, productValue } = data;
          if (status == 200) {
            let message = {
              // 商品描述
              store_name: storeInfo.store_name,
              // 价格
              price: storeInfo.price,
              // 原价价
              ot_price: storeInfo.ot_price,
              // vip价
              vip_price: storeInfo.vip_price,
              // 库存
              stock: storeInfo.stock,
              // 销量
              sales: storeInfo.sales,
            };
            this.$route.meta.title = message.store_name
            document.title = message.store_name
            let array = [];
            // // 切分精品推荐
            for (let i = 0; i < Math.ceil(good_list.length / 6); i++) {
              let arr = [];
              // 0 6
              arr = good_list.slice(i * 6, 6 * (i + 1));

              array.push(arr);
            }

            this.slider_image = storeInfo.slider_image;
            this.message = message;
            this.good_list = array;
            this.description = storeInfo.description;
            this.userCollect = storeInfo.userCollect;
            // for (let i = 0; i <productAttr.length; i++) {
            //   if (productAttr[i].attr_name == "尺码") {
            //     this.size = this.productAttr[i].attr_value[0].attr;
            //     this.sizeVissably = true;
            //   }
            //   if (productAttr[i].attr_name == "颜色") {
            //     this.color = productAttr[i].attr_value[0].attr;
            //     this.colorVissably = true;
            //   }
            // }

            // console.log("这是属性组合", productValue);
            if (productAttr.length == 0) {
              return false;
            } else {
              this.productAttr = productAttr;

              let colorList = [];
              let sizeList = [];

              for (let i = 0; i < productAttr.length; i++) {
                if (productAttr[i].attr_name == "尺码") {
                  this.sizeList = productAttr[i].attr_value;
                  this.sizeVissably = true;
                }
                if (productAttr[i].attr_name == "颜色") {
                  this.colorList = productAttr[i].attr_value;
                  this.colorVissably = true;
                }
              }

              this.productValue = productValue;

              let key = Object.keys(productValue)[0];

              if (key.includes(",")) {
                this.index = key.split(",")[0];
                this.square = key.split(",")[1];
                this.size = this.index;
                this.color = this.square;
              } else {
                if (key.includes("色")) {
                  this.color = key;
                  this.square = key;
                } else {
                  this.index = key;
                  this.size = key;
                }
              }

              this.image = productValue[key].image;
              this.price = productValue[key].price;
              this.sales = productValue[key].sales;
              this.stock = productValue[key].stock;
              this.suk = productValue[key].suk;
              this.unique = productValue[key].unique;

              console.log(Object.keys(productValue)[0]);
            }

            // this.getAttrValue()
          }
        })
        .catch((err) => {
          console.log("商品详情获取失败");
        });
    },
    // 添加收藏
    addCollection() {
      let obj = {};

      if (this.isCollect) {
        this.removeCollect(this.productId);
        this.$toast.show("取消收藏", 500);
      } else {
        obj.id = this.productId;
        obj.price = this.message.price;
        obj.store_name = this.message.store_name;
        obj.image = this.slider_image[0];

        // 添加收藏
        this.addCollect(obj);
        this.$toast.show("添加成功", 500);
      }

      this.isCollect = !this.isCollect;
    },

    // 打开属性选择器
    openAttr2(val) {
      this.isShowAttr = val;
    },

    getCollect(val) {
      this.userCollect = val;
    },
    // 打开/关闭属性选择器
    openAttr() {
      if (this.isShowAttr) {
        // 添加购物车
        this.addCart();
        this.$toast.show("添加购物车成功", 1000);
      } else {
        this.isShowAttr = true;
      }

      // console.log(this.isShowAttr);
    },
    // 关闭属性选择器
    closeAttr(val) {
      this.isShowAttr = false;
    },

    clickSize(str) {
      this.index = str;
      this.size = str;

      this.getAttrValue();
    },

    clickColor(str) {
      this.square = str;
      this.color = str;

      this.getAttrValue();
    },

    getAttrValue() {
      this.count = 1;
      if (this.size && this.color) {
        this.key = this.size + "," + this.color;
      } else if (this.size || this.color == "") {
        this.key = this.size;
      } else if (this.color || this.size == "") {
        this.key = this.color;
      } else if (this.color == "" && this.size == "") {
        return;
      }

      for (let key in this.productValue) {
        if (this.key == key) {
          this.image = this.productValue[key].image;

          this.price = this.productValue[key].price;
          this.sales = this.productValue[key].sales;
          this.stock = this.productValue[key].stock;
          this.suk = this.productValue[key].suk;
          this.unique = this.productValue[key].unique;
        }
      }
    },

    // 增加商品
    addCount() {
      if (this.stock == null) {
        if (this.message.stock == 0) {
          return;
        }

        if (this.count >= this.message.stock) {
          this.count = this.message.stock;
          return;
        }
      } else {
        if (this.stock == 0) {
          return;
        }

        if (this.count >= this.stock) {
          this.count = this.stock;
          return;
        }
      }
      this.count += 1;
    },
    // 减少商品
    subCount() {
      if (this.stock == null) {
        if (this.message.stock == 0) {
          return;
        }

        if (this.count <= 1) {
          this.count = 1;
          return;
        }
      } else {
        if (this.stock == 0) {
          return;
        }

        if (this.count <= 1) {
          this.count = 1;
          return;
        }
      }
      this.count -= 1;
    },

    tab(tabIndex) {
      this.tabIndex = tabIndex;
      // let arr = [];

      // for (let i in this.$refs) {
      //   arr.push(i);
      // }

      // arr.some((item, index) => {
      //   if (this.tabIndex == index) {
      //     // if( i == tabIndex){
      //     console.log(this.$refs[item].offsetTop);

      //     let distance = 0;
      //     if (tabIndex == 0) {
      //       distance = 0;
      //     } else {
      //       distance = this.$refs[item].offsetTop - 48;
      //     }
      //     window.scroll(0, distance);
      //     //    console.log(this.$refs[i].offsetTop)
      //     return;
      //     // }
      //   }
      // });
      this.flag = false
      this.ds = this.distance[this.tabIndex]

        this.animate(window,this.ds,()=>{
            this.flag = true
            console.log("揍你")
        })
    },

    animate(obj,target,callback){
      if(obj.timer){
        clearInterval(obj.timer)
      }

      obj.timer = setInterval(()=>{
        let step = (target - window.pageYOffset) / 10
        step = step > 0 ? Math.ceil(step) : Math.floor(step);
        if(window.pageYOffset == target){
          clearInterval(obj.timer)
          callback && callback()
        }

        window.scroll(0,window.pageYOffset + step)
      },15)
    }
  },
  mounted() {
    this.$nextTick(() => {
      let arr = [];
      for (let i in this.$refs) {
        arr.push(i);
      }

      arr.some((item, index) => {
        this.distance.push(this.$refs[item].offsetTop);
      });

      console.log(this.distance);
    });

    let collectData = JSON.parse(localStorage.getItem("collection"));

    

    window.addEventListener("scroll", () => {
      if (this.flag) {
        
        this.ds = window.pageYOffset
        for (let i = 0; i < this.distance.length; i++) {
          if (this.distance[i + 1]) {
            if (
              window.pageYOffset >= this.distance[i] &&
              window.pageYOffset <= this.distance[i + 1] - 48
            ) {
              this.tabIndex = i;
              return;
            }
          } else {
            if (window.pageYOffset >= this.distance[i]) {
              this.tabIndex = i;
            }

            return;
          }
        }
      } else {
        return;
      }


    });
  


   
  
  
  
  },
  destroyed() {
     
    window.removeEventListener("scroll", window, false);
  },
};
</script>

<style lang="scss" scoped>
.detail_container {
  padding-bottom: 70px;
}

.header {
  position: fixed;
  width: 100%;
  z-index: 100;
  height: 48px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-bottom: 0.01rem solid #eee;
  
  transition: all 0.2s ease;
  .nn_tiem {
    padding: 0 15px;
    color: #282828;
    font-size: 15px;
    height: 38px;
    padding-top: 8px;
    span {
      display: block;
      padding: 2px 0;
      font-size: 15px;
    }
  }
  .nn_tiem.active span {
    border-bottom: 3px solid #fc4141;
  }
}

.select {
  display: flex;
  justify-content: space-between;
  height: 40px;
  background-color: #fff;
  padding: 0 15px;
  margin: 10px 0;
  .ss_lef {
    line-height: 40px;
    color: #82848f;
    font-size: 13px;
    span {
      font-size: 14px;
      color: #282828;
    }
  }
  .icon {
    line-height: 40px;
    img {
      width: 20px;
      height: 20px;
    }
  }
}

.pj {
  height: 40px;
  padding: 0 15px;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  .pl {
    color: #282828;
    font-size: 14px;
  }
  .pr {
    font-size: 14px;
    color: #808080;
    span {
      color: #fc4141;
    }
    i {
      display: inline-block;
      width: 20px;
      height: 20px;
      background: url(../../assets/icon/common/right_arrow.svg) no-repeat;
      background-size: 100% 100%;
      vertical-align: middle;
      margin-top: -2px;
      margin-left: -15px;
    }
  }
}

.footer {
  position: fixed;
  width: 100%;
  left: 0;
  bottom: 0;
  z-index: 11111;
  background-color: #fff;
  height: 50px;
  padding: 0 15px;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #f0f0f0;
  > div {
    height: 50px;
  }
  .dj_com {
    font-size: 12px;
    color: #666;
    // padding: 0 3px;
    // width: 50px;
    > img {
      display: block;
      width: 20px;
      height: 20px;
      margin: 10px auto 0;
    }
  }

  .btns {
    display: flex;
    align-items: center;
    > div {
      height: 38px;
      width: 111px;
      font-size: 14px;
      color: #fff;
      text-align: center;
      line-height: 38px;
    }
    .addCart {
      border-top-left-radius: 19px;
      border-bottom-left-radius: 19px;
      background-image: -webkit-gradient(
        linear,
        left top,
        right top,
        from(#fea10f),
        to(#fa8013)
      );
      background-image: linear-gradient(90deg, #fea10f 0, #fa8013);
    }
    .buy {
      border-top-right-radius: 19px;
      border-bottom-right-radius: 19px;
    }
    .buy.bgc1 {
      background-color: #bbb !important;
    }
    .buy.bgc2 {
      background-image: -webkit-gradient(
        linear,
        left top,
        right top,
        from(#fa6514),
        to(#e93323)
      );
      background-image: linear-gradient(90deg, #fa6514 0, #e93323);
    }
  }
}

.my-swipe .van-swipe-item {
  color: #fff;
  font-size: 20px;
}

.bg1 {
  // background-color: pink;
}
.bg2 {
  background-color: red;
}

.attr-enter-active {
  animation: show 0.5s ease;
}
.attr-leave-active {
  animation: hide 0.5s ease;
}

@keyframes show {
  0% {
    transform: translateY(100%);
  }
  100% {
    transform: translateY(0);
  }
}
@keyframes hide {
  0% {
    transform: translateY(0%);
  }
  100% {
    transform: translateY(100%);
  }
}

.mask {
  position: fixed;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 10;
  left: 0;
  top: 0;
}

.MySize {
  position: fixed;
  width: 100%;
  bottom: 0;
  left: 0;
  z-index: 110;
  padding: 13px 15px 60px;
  background-color: #fff;
  border-top-right-radius: 15px;
  border-top-left-radius: 15px;
  //   position: relative;
  .info {
    height: 75px;
    display: flex;
    .img {
      width: 75px;
      height: 75px;
      border-radius: 8px;
      overflow: hidden;
      > img {
        width: 100%;
        height: 100%;
      }
    }

    .inf {
      width: 205px;
      height: 75px;
      margin-left: 15px;
      .store_name {
        width: 100%;
        color: #202020;
        font-size: 16px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .tp {
        margin-top: 27px;
        font-size: 12px;
        color: #fc4141;
        .price {
          font-size: 18px;
        }
        .store {
          margin-left: 15px;
          color: #999;
        }
      }
    }
  }
  .ty_com {
    margin-top: 18px;
    .ty_td {
      color: #999;
      font-size: 15px;
    }
  }
  .size {
    .item {
      span {
        display: inline-block;
        border: 1px solid #bbb;
        padding: 4px 16px;
        font-size: 13px;
        color: #202020;
        border-radius: 3px;
        margin: 5px 5px 0 0;
      }
      span.active {
        background-color: #ff3700;
        color: #fff;
      }
    }
  }
  .color {
    .item {
      span {
        display: inline-block;
        border: 1px solid #bbb;
        padding: 4px 16px;
        font-size: 13px;
        color: #202020;
        margin: 5px 5px 0 0;
        border-radius: 3px;
      }

      span.active {
        background-color: #ff3700;
        color: #fff;
      }
    }
  }
  .count {
    .count_com {
      margin-top: 5px;
      display: flex;
      height: 27px;
      width: 99px;
      border-radius: 3px;
      border: 1px solid #e3e3ee;
      color: #dedede;
      font-size: 22px;
      > div {
        flex: 1;
        line-height: 27px;
        text-align: center;
      }
      .num {
        font-size: 13px;
        border-left: 1px solid #e3e3ee;
        border-right: 1px solid #e3e3ee;
        color: #333;
      }
    }
  }

  .closeBtn {
    position: absolute;
    top: 13px;
    right: 15px;
    width: 15px;
    height: 15px;
    > img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>

